<template>
  <view class="content" v-if="load">
    <image class="imgage" src="@/static/image/home/backdrop.png" mode=""></image>
    <swiper :indicator-dots="true" circular="true" :autoplay="true" indicator-active-color="#ff8104" class="swiper">
      <swiper-item v-for="(item, index) in constData.applet_image" :key="index">
        <image :src="item" />
      </swiper-item>
    </swiper>

    <view class="price">
      <view class="hands">到手价</view>
      <text class="currentPrice">￥{{ constData.actual_amount }}</text>
      <text class="original">原价￥{{ constData.origin_amount }}</text>
    </view>

    <view class="title">{{ constData.product_name }}</view>

    <view class="subheading">
      <view v-show="constData.service" class="shb_text">
        <text>服务</text>
        <text>{{ constData.service || "" }}</text>
      </view>
      <view v-show="constData.notice" class="shb_text">
        <text class="xuzhi">须知</text>
        <text>{{ constData.notice || "" }}</text>
      </view>
      <view v-show="constData.store" class="shb_text">
        <text>门店</text>
        <text>{{ constData.store || "" }}</text>
      </view>
      <view @click="callphone(constData.customerService[1].value)" class="shb_texta">
        <text>热线服务</text>
        <text>{{
          constData.customerService[0].title +
          constData.customerService[0].value
        }}</text>
      </view>
      <view v-show="constData.sku_type === 1">
        <view v-for="(item, index) in constDataSkus" :key="item.skuId" class="Addpurchase">
          <view class="jg">加购<text class="blackfont">&nbsp;&nbsp;{{ item.explain
              }}<text style="color: red">￥{{ item.price }}</text>/{{ item.unit }}</text>
          </view>
          <view class="progress flexC">
            <view class="text">加购数量</view>
            <view class="flex-c proG">
              <view @click="advance(false, index)" class="flex-c">-</view>
              <view class="flex-c">{{ item.buyMore + 1 }}</view>
              <view @click="advance(true, index)" class="flex-c">+</view>
            </view>
          </view>
          <view v-show="item.buyMore > 0" class="red">已加购{{ Number(item.buyMore) * Number(item.increment)
            }}{{ item.numUnit }}，共计{{
              Number(item.quantity) +
              Number(item.buyMore) * Number(item.increment)
            }}{{ item.numUnit }}，合计{{
              Number(constData.actual_amount) + item.price * item.buyMore
            }}元
          </view>
        </view>
      </view>
    </view>
    <view @click="toEvaluate(constData.product_id)" class="reputation">
      <view class="rep-l">
        <image src="@/static/image/home/pingj.png" mode=""></image>
        <text>团购评价（{{
          constData.evaluate_num < 1000 ? constData.evaluate_num : "999+" }}条）</text>
      </view>
      <view class="rep-r">
        <text>查看全部</text>
        <image src="@/static/image/home/arrow.jpg" mode=""></image>
      </view>
    </view>
    <view @click="toEvaluate(constData.product_id)" class="evale">
      <view class="evaluate" v-for="item in constData.evaluate">
        <view class="evaName">
          <image :src="item.avatar" mode=""></image>
          <text>{{ item.nickname }}</text>
          <view>已消费</view>
          <view class="view2">回头客</view>
        </view>
        <view class="evaText">
          {{ item.content }}
        </view>
      </view>
    </view>

    <view class="image-container">
      <image :src="constData.details_images[0]" mode="widthFix" class="original-image" :lazy-load="true" />
    </view>
    <view :style="{ 'padding-bottom': $getBottomHight() + 'px' }" style="height: 100rpx"></view>
    <view :style="{ 'padding-bottom': $getBottomHight() + 'px' }" class="bottomBtn">
      <view class="customer">
        <button data-biz-lin="1" data-im-type="goods" :data-goods-id="constData.product_id" :data-im-id="dataImId"
          open-type="im"></button>
        <image src="@/static/image/home/service.png" mode=""></image>
        <text>客服</text>
      </view>
      <view class="btnprice">￥{{ Number(constData.actual_amount) + totalPricea }}</view>
      <text class="originMount">￥{{ constData.origin_amount }}</text>
      <view @click="bottomPop" class="btns"> 立即购买 </view>
    </view>
    <uv-popup ref="popup" overlay="true" mode="bottom" closeOnClickOverlay="false" round="20"
      custom-style="height: 1000rpx;width:96%;margin:auto">
      <select-sku @close="closePopup" :productId="id" @skusData="receiveSkus" />
    </uv-popup>
  </view>
</template>

<script>
import selectSku from "@/components/selectSku/selectSku.vue";
import { mapGetters, mapActions } from "vuex";
import { getGoodsDetails, position } from "@/api/home.js";
import { setTiktokIm } from "@/api/my.js";
const plugin = tt.requirePlugin('tta5a3d31e3aecfb9b11');
export default {
  components: {
    selectSku,
  },
  data() {
    return {
      load: false,
      constDataSkus: [],
      skusData: {},
      skusPrice: [],
      csamount: 1,
      skubuMore: 0,
      id: null, // 商品id
      content: "<div>富文本</div>",
      constData: {},
      dataImId: "77187188122",
      height: 0,
      x: "",
      y: "",
      type: "",
      totalPricea: 0,
      // discountId: ''
      calResult: {},
      goodsMarkList: [],
      orderMarket: {}
    };
  },
  onLoad(details) {
    if (!details.id) {
      uni.navigateBack();
      return false;
    }
    this.id = details.id;
    this.getLocation();
    this.getTiktokIm();
    this.goodsDetails();
  },
  computed: {
    ...mapGetters("user", ["isLogin"]),
  },
  methods: {
    closePopup() {
      this.$refs.popup.close();
    },
    ...mapActions("user", ["silentLogin"]),
    getLocation() {
      let that = this;
      uni.getLocation({
        type: "wgs84",
        success: (res) => {
          that.x = res.longitude;
          that.y = res.latitude;
          that.type = 1;
        },
        fail: (error) => {
          that.type = 2;
          //点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
          uni.showModal({
            title: "获取位置信息提示",
            content: "是否允许授权获取您的位置信息用于精确提供本地服务",
            cancelText: "取消",
            cancelColor: "#999",
            confirmText: "确定",
            confirmColor: "#f94218",
            success(res) {
              if (res.confirm) {
                // 选择弹框内授权
                uni.openSetting({
                  success(res) {
                    uni.getLocation({
                      type: "wgs84",
                      success: (res) => {
                        that.x = res.longitude;
                        that.y = res.latitude;
                        that.type = 1;
                      },
                    });
                  },
                });
              } else if (res.cancel) {
                // 选择弹框内 不授权
                uni.showModal({
                  title: "提示",
                  content:
                    "抱歉!由于不能获取您的定位，无法确定您所在区域是否可接单，暂时不可下单!",
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                    }
                  },
                });
              }
            },
          });
        },
      });
    },
    receiveSkus(row) {
      this.skusData = row;
      uni.showLoading({ title: "加载中" });
      const { explain, price, skuId } = this.skusData;
      plugin.createOrder({
        skuList: [
          {
            skuId: skuId,
            quantity: 1,
            price: price * 100,
            skuType: 2,
            goodsInfo: {
              goodsName: explain,
              goodsPhoto: "",
              goodsId: this.constData.product_id,
              goodsType: 1,
            },
          },
        ],
        payment: {
          totalAmount: price * 100,
        },
        success: (res) => {
          this.$refs.popup.close();
          const orderid = res.orderId;
          uni.navigateTo({
            url: `/pages/Paymentsuccess/Paymentsuccess?orderid=${orderid}&id=${this.id}`,
          });
        },
        fail: (arr) => {
          this.$refs.popup.close();
          if (arr.outOrderNo) {
            this.$showToast("支付取消");
          } else {
            this.$showToast("支付失败");
          }
        },
        complete: () => {
          uni.hideLoading();
        },
      });
    },
    callphone(phoneNumber) {
      uni.makePhoneCall({
        phoneNumber,
      });
    },
    setPayment() {
      //先约后买
      // uni.navigateTo({
      //   url: `/pages/goubuy/goubuy?id=${this.id}&buymore=${this.skubuMore}`,
      // });
      // 先买后约
      if (this.constData.sku_type === 2) {
        this.$refs.popup.open();
      } else {
        uni.showLoading({ title: "加载中" });
        const { product_id, actual_amount, product_name, image_list_images } =
          this.constData;
        var order_amount = actual_amount;
        const createOrder = (
          skuList,
          totalAmount,
          successCallback,
          failCallback,
          completeCallback
        ) => {
          plugin.createOrder({
            skuList: skuList,
            payment: {
              totalAmount: totalAmount,
            },
            tradeOption: {
              life_trade_flag: 1,// 0：非融合链路（默认值）  1：走融合链路（标准融合/完全融合）
            },
            discountInfo: {
              type: 2,
              detail: {
                orderDiscount: {
                  orderTotalDiscountAmount: 0,
                  goodsTotalDiscountAmount: this.calResult.totalDiscountAmount,
                  marketingInfo: [
                    {
                      discountAmount: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].discountAmount,
                      discountRange: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].discountRange,
                      id: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].id,
                      note: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].note,
                      subtype: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].subtype,
                      title: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].title,
                      type: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].type
                    },
                  ],
                },
                goodsDiscount: [
                  {
                    goodsId: this.goodsMarkList[0].goodsId,
                    quantity: this.goodsMarkList[0].quantity,
                    totalAmount: this.goodsMarkList[0].totalAmount,
                    totalDiscountAmount: this.calResult.totalDiscountAmount,
                    skuId: this.calResult.skuId,
                    marketingInfo: [
                      {
                        discountAmount: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].discountAmount,
                        discountRange: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].discountRange,
                        id: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].id,
                        note: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].note,
                        subtype: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].subtype,
                        title: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].title,
                        type: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].type
                      },
                    ],
                  },
                ],
                itemDiscount: [
                  {
                    goodsId: this.goodsMarkList[0].goodsId,
                    totalAmount: this.goodsMarkList[0].totalAmount,
                    totalDiscountAmount:this.calResult.totalDiscountAmount,
                    marketingInfo: [
                      {
                        discountAmount: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].discountAmount,
                        discountRange: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].discountRange,
                        id: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].id,
                        note: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].note,
                        subtype: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].subtype,
                        title: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].title,
                        type: this.calResult.itemCalculationResultInfo[0].marketingDetailInfo[0].type
                      },
                    ],
                  },
                ],
              },
            },
            success: successCallback,
            fail: failCallback,
            complete: completeCallback,
          });
        };
        const generateSku = (
          skuList,
          product_id,
          product_name,
          image_list_images,
          constDataSkus
        ) => {
          skuList.push({
            skuId: product_id,
            quantity: 1,
            price: order_amount * 100,
            skuType: 1,
            goodsInfo: {
              goodsName: product_name,
              goodsPhoto: image_list_images[0],
              goodsId: product_id,
              goodsType: 1,
            },
          });
          constDataSkus.forEach((element) => {
            if (element.buyMore > 0) {
              skuList.push({
                skuId: element.skuId,
                quantity: element.buyMore,
                price: element.price * 100,
                skuType: 2,
                goodsInfo: {
                  goodsName: product_name,
                  goodsPhoto: image_list_images[0],
                  goodsId: product_id,
                  goodsType: 1,
                },
              });
              order_amount =
                Number(order_amount) + element.price * element.buyMore;
            }
          });
          if (skuList.length > 1) {
            skuList[0].skuType = 2;
          }
        };
        const skuList = [];
        generateSku(
          skuList,
          product_id,
          product_name,
          image_list_images,
          this.constDataSkus
        );
        createOrder(
          skuList,
          order_amount * 100,
          (res) => {
            if (res) {
              const orderid = res.orderId;
              uni.navigateTo({
                url: `/pages/Paymentsuccess/Paymentsuccess?orderid=${orderid}&id=${this.id}`,
              });
            }
          },
          (arr) => {
            console.log(arr)
            if (arr.outOrderNo) {
              this.$showToast("支付取消");
            } else {
              this.$showToast("支付失败");
            }
          },
          () => {
            uni.hideLoading();
          }
        );
      }
    },
    bottomPop() {
      position({
        type: this.type,
        longitude: this.x,
        latitude: this.y,
      }).then((res) => {
        if (res.code === 1) {
          if (!this.isLogin) {
            uni.navigateTo({ url: "/pages/login/login" });
            this.silentLogin(undefined, true).then((res) => {
              this.setPayment();
            });
            return false;
          }
          this.setPayment();
        } else {
          uni.showModal({
            title: "提示",
            content: res.msg,
            showCancel: false,
            success: function (res) { },
          });
        }
      });
    },
    getTiktokIm() {
      setTiktokIm().then((res) => {
        if (res.code === 1) {
          this.dataImId = res.data;
        }
      });
    },
    toEvaluate(id) {
      uni.navigateTo({
        url: "/pages/evaluate/evaluate?id=" + id,
      });
    },
    goodsDetails() {
      getGoodsDetails({
        id: this.id,
      }).then((res) => {
        if (res.code === 1) {
          this.constData = res.data;
          if (res.data.skus !== undefined) {
            this.constData.skus.forEach((element) => {
              element.buyMore = 0;
              this.skusPrice[element.skuId] = element.price;
            });
          }
          this.constDataSkus = this.constData.skus;
          this.load = true;
          this.promition()
        }
      });
    },
    promition() {
      const { product_id, actual_amount, product_name, image_list_images } =
        this.constData;
      tt.computePromotion({
        goodsMarketingInfo: [{
          goodsId: product_id,
          quantity: 1,
          totalAmount: actual_amount * 100
        }],
        needDefaultMarketing: true, // 需要返回默认优惠
        success: (res) => {
          console.log(res)
          this.calResult = res.calculationResult
          this.goodsMarkList = res.goodsMarketingList
          this.orderMarket = res.orderMarketing
        },
        fail: (res) => {
          console.log(res.calculationResult.itemCalculationResultInfo[0].marketingDetailInfo[0].code);
        },
      });
    },
    advance(judge, index) {
      const updatedSkus = { ...this.constDataSkus[index] };
      if (judge) {
        updatedSkus.buyMore < 50 && updatedSkus.buyMore++;
      } else {
        updatedSkus.buyMore > 0 && updatedSkus.buyMore--;
      }
      this.skubuMore = updatedSkus.buyMore
      this.$set(this.constDataSkus, index, updatedSkus);
      let totalPrice = 0;
      this.constDataSkus.forEach((item) => {
        const itemTotal = item.price * item.buyMore;
        totalPrice += itemTotal;
      });
      this.totalPricea = totalPrice;
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  padding: 40rpx 25rpx;
  background-color: #fff;

  .uv-popup::v-deep {
    .uv-popup__content::v-deep {
      width: 92;
      margin: auto;
    }
  }

  .imgage {
    position: absolute;
    width: 100%;
    height: 200rpx;
    top: 0;
    right: 0;
  }
}

.bottomBtn {
  width: 100%;
  height: 100rpx;
  position: fixed;
  bottom: 0;
  border-top: #e5e5e5 solid 2rpx;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  z-index: 9999;

  .customer {
    height: 56rpx;
    width: 116rpx;
    border-radius: 38rpx;
    border: #7e7e7e 1rpx solid;
    margin-left: 22rpx;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    position: relative;

    button::after {
      border: none;
      background-color: none;
    }

    button {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 175rpx;
      height: 73rpx;
      background-color: inherit;
      z-index: 99999;
    }

    image {
      width: 36rpx;
      height: 38rpx;
      margin-right: 4rpx;
    }

    text {
      color: #7e7e7e;
      font-weight: bold;
      font-size: 20rpx;
    }
  }

  .btnprice {
    font-size: 44rpx;
    color: #ff8104;
    font-weight: bold;
  }

  .originMount {
    color: #ccc;
    text-decoration: line-through;
    font-size: 26rpx;
  }

  .btns {
    background: #ff8104;
    color: #fff;
    border-radius: 38rpx;
    width: 320rpx;
    height: 75rpx;
    margin-right: 22rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30rpx;
  }
}

.evale {
  margin-bottom: 50rpx;

  .evaluate:nth-of-type(1) {
    padding-bottom: 26rpx;
    border-bottom: #f3f3f3 solid 2rpx;
  }
}

.image-container {
  display: flex;
  justify-content: center;

  .original-image {
    display: block;
    width: 100%;
    max-width: 100%;
  }
}

.evaluate {
  margin-top: 26rpx;

  .evaText {
    padding-left: 76rpx;
    font-weight: 400;
    color: #1c2023;
    font-size: 28rpx;
    padding-right: 10rpx;
    overflow: hidden; //超过隐藏
    text-overflow: ellipsis; //设置省略号
    -webkit-line-clamp: 2;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }

  .evaName {
    display: flex;
    align-items: center;

    image {
      width: 60rpx;
      height: 60rpx;
      border-radius: 100%;
    }

    text {
      color: #1c2023;
      font-weight: 500;
      font-size: 26rpx;
      padding: 0 16rpx;
    }

    view {
      background-color: #d5e8fc;
      border-radius: 20rpx;
      font-size: 24rpx;
      color: #4671c6;
      padding: 2rpx 10rpx;
    }

    .view2 {
      color: #ff8104 !important;
      background-color: #ffd4a8 !important;
      margin-left: 16rpx;
    }
  }
}

.reputation {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: bold;
  margin-top: 35rpx;

  .rep-r {
    display: flex;
    align-items: center;
    justify-content: center;

    image {
      width: 16rpx;
      height: 16rpx;
      margin-left: 5rpx;
    }

    text {
      color: #606972;
      font-size: 24rpx;
    }
  }

  .rep-l {
    display: flex;
    align-items: center;
    justify-content: center;

    image {
      width: 30rpx;
      height: 27rpx;
      margin-right: 12rpx;
    }

    text {
      color: #1c2023;
      font-size: 28rpx;
    }
  }
}

.subheading {
  color: #606972;
  font-weight: 400;
  font-size: 26rpx;
  margin-top: 35rpx;
  padding-bottom: 35rpx;
  border-bottom: #f3f3f3 solid 2rpx;

  .flexC {
    display: flex;
    align-items: center;
  }

  .Addpurchase {
    margin-top: 60rpx;

    .jg {
      font-size: 30rpx;

      .blackfont {
        color: #1c2023;
        margin-left: 16rpx;
      }
    }

    .progress {
      justify-content: space-around;
      margin-top: 20rpx;
      margin-bottom: 20rpx;

      .flex-c {
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .proG {
        font-size: 28rpx;
        margin-right: -80rpx;

        view:nth-child(1) {
          border: #979a9d 1rpx solid;
          border-radius: 60rpx 0 0 60rpx;
        }

        view:nth-child(2) {
          border-top: #979a9d 1rpx solid;
          border-bottom: #979a9d 1rpx solid;
          font-weight: bold;
          width: 70rpx !important;
        }

        view:nth-child(3) {
          border: #979a9d 1rpx solid;
          border-radius: 0 60rpx 60rpx 0;
        }

        view {
          flex: 1;
          width: 60rpx;
          height: 60rpx;
        }
      }

      .text {
        color: #1c2023;
        font-size: 28rpx;
        margin-right: 60rpx;
      }
    }

    .red {
      color: red;
    }
  }

  .shb_text {
    display: flex;
    align-items: center;

    text:nth-child(1) {
      width: 12%;
    }

    text:nth-child(2) {
      width: 88%;
    }
  }

  .shb_texta {
    display: flex;
    align-items: center;

    text:nth-child(1) {
      width: 20%;
    }

    text:nth-child(2) {
      width: 80%;
    }

    margin-top: 20rpx;
  }

  .shb_text:nth-child(2) {
    margin: 20rpx 0;
  }
}

.title {
  font-size: 38rpx;
  font-weight: bold;
  color: #1c2023;
  margin-top: 40rpx;
}

.price {
  display: flex;
  align-items: center;
  margin-top: 30rpx;
  font-family: PingFang SC;
  font-weight: 500;

  .hands {
    height: 40rpx;
    background: #d5e8fc;
    width: 100rpx;
    border-radius: 40rpx;
    font-size: 24rpx;
    color: #4671c6;
    text-align: center;
    line-height: 40rpx;
  }

  .currentPrice {
    color: #ff8104;
    font-size: 38rpx;
    margin: 0 20rpx;
  }

  .original {
    font-size: 24rpx;
    color: #606972;
    text-decoration: line-through;
  }
}

.swiper {
  height: 350rpx;
  border-radius: 10rpx;

  image {
    width: 100%;
    height: 100%;
    border-radius: 10rpx;
  }
}
</style>